import csv
import os

def parse_cif_line(line):
    """
    Parse a single line of CIF file into a list of values.
    """
    # Split the line based on whitespace (space or tab)
    parts = line.split()
    return parts

def convert_cif_to_csv(cif_folder_path, csv_folder_path):
    """
    Convert CIF files in the given folder to CSV files, preserving all columns.
    """
    # Ensure the output directory exists
    if not os.path.exists(csv_folder_path):
        os.makedirs(csv_folder_path)

    # Loop through all CIF files in the provided folder
    for cif_filename in os.listdir(cif_folder_path):
        if cif_filename.endswith('.cif'):
            cif_filepath = os.path.join(cif_folder_path, cif_filename)
            
            with open(cif_filepath, 'r') as cif_file:
                lines = cif_file.readlines()
                
                # Prepare rows for CSV
                rows = []
                for line in lines:
                    # Skip empty lines or lines that do not start with 'ATOM'
                    if line.strip() and line.startswith('ATOM'):
                        # Parse the line and append to rows
                        parsed_line = parse_cif_line(line)
                        rows.append(parsed_line)
                
                # Write to CSV
                csv_filename = os.path.splitext(cif_filename)[0] + '.csv'
                csv_filepath = os.path.join(csv_folder_path, csv_filename)
                
                with open(csv_filepath, 'w', newline='') as csv_file:
                    csv_writer = csv.writer(csv_file)
                    # Write rows without headers
                    csv_writer.writerows(rows)

# Example usage
cif_folder_path = r'C:\Users\jakea\Desktop\new CaM alphafold\cyanobacteria models'
csv_folder_path = r'C:\Users\jakea\Desktop\new CaM alphafold\cyanobacteria models\csv'
convert_cif_to_csv(cif_folder_path, csv_folder_path)
